package com.course.server.service;

import cn.hutool.core.util.StrUtil;
import com.course.server.dto.TeacherDto;
import com.course.server.dto.PageDto;
import com.course.server.entity.Teacher;
import com.course.server.entity.TeacherExample;
import com.course.server.mapper.TeacherMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Durian
 * @date: 2021/5/3 12:32
 */
@Service
public class TeacherService {

    @Resource
    private TeacherMapper teacherMapper;

    public PageDto<TeacherDto> list(int page, int size) {
        PageHelper.startPage(page, size);
        TeacherExample example = new TeacherExample();
        // criteria只能一次
        TeacherExample.Criteria criteria = example.createCriteria();
        // service层尽量灵活
        List<Teacher> teachers = teacherMapper.selectByExample(example);
        PageInfo<Teacher> pageInfo = new PageInfo<>(teachers);

        List<TeacherDto> teacherDtos = CopyUtil.copyList(teachers, TeacherDto.class);
        PageDto<TeacherDto> pageDto = new PageDto<>();
        pageDto.setPage(page);
        pageDto.setSize(size);
        pageDto.setList(teacherDtos);
        pageDto.setTotal(pageInfo.getTotal());
        return pageDto;
    }

    public List<TeacherDto> listAll() {
        TeacherExample example = new TeacherExample();
        return CopyUtil.copyList(teacherMapper.selectByExample(example), TeacherDto.class);
    }

    public void save(TeacherDto teacherDto) {
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherDto, teacher);
        if (StrUtil.isBlank(teacherDto.getId())) {
            insert(teacher);
        } else {
            update(teacher);
        }
    }

    public void delete(String id) {
        teacherMapper.deleteByPrimaryKey(id);
    }

    private void insert(Teacher teacher) {
        teacher.setId(UuidUtils.getShortUuid());
        teacherMapper.insert(teacher);
    }

    private void update(Teacher teacher) {
        teacherMapper.updateByPrimaryKeySelective(teacher);
    }

}
